package fr.imag.adele.mediation.probes.impl;

import java.util.Date;

import fr.imag.adele.mediation.probes.services.DataProcessingElement;
import fr.imag.adele.mediation.probes.services.DataSender;
import fr.imag.adele.mediation.probes.services.DataCollector;
import fr.imag.adele.mediation.probes.services.Probe;
import fr.imag.adele.mediation.probes.services.Scheduler;
import fr.imag.adele.mediation.probes.util.DataSet;

public class StandardProbe implements Probe { 
	private DataCollector 		  	m_dataCollector;
	private DataSender 			  	m_dataSender;
	private DataProcessingElement	m_dataProcessingElements;
	private Scheduler 			  	m_scheduler;
	private String 				  	m_probeId;
	
	private boolean 			  	m_working;
	
	public void start() {
		//Thread t = new Thread(this);
		if (m_dataCollector != null) m_dataCollector.setParentProbe(this);
		if (m_scheduler != null) m_scheduler.setParentProbe(this);
		m_working=true;	
		//t.start();
	}
	
	public void stop() {
		m_working=false;
	}
	/*
	 * change all the calculated data to have the current probe as source,
	 * and affect it a new timestamp.
	 */
	protected DataSet handleData(DataSet dataSet){		
		if (dataSet != null){
			for (int i=0;i<dataSet.size(); i++){
				dataSet.getDataEvent(i).setSource(m_probeId);
				dataSet.getDataEvent(i).setTimeStamp(new Date().toString());
			}			
		} 
		return dataSet;
	}
	
	public void process(){
		if (m_working ==true){
			DataSet tmpDataSet = new DataSet();
			//tmpDataSet.add(new DataEvent(m_probeId,"cpu1",new Date().toString(), "34", "%", null));
			if (m_dataCollector != null)
				tmpDataSet = m_dataCollector.getCollectedData();
			else
				System.out.println("No DataCollector found!");
			// process the data
			if (m_dataProcessingElements != null)
				tmpDataSet = m_dataProcessingElements.process(tmpDataSet);
			else 
				System.out.println("No DataProcessingElement found!");
			// change the events source
			tmpDataSet = handleData(tmpDataSet);
			// send the data
			if (m_dataSender != null) 
				m_dataSender.sendData(tmpDataSet);
			else
				System.out.println("No DataSender found!");
			/*for (int i=0; i<m_dataProcessingElements.length; i++){
				if (m_dataProcessingElements[i] != null) {				
					m_dataProcessingElements[i].process(tmpDataSet);
				}
			}*/
		}
	}
	
	public String getProbeId(){
		return m_probeId;
	}
	public Scheduler getScheduler(){
		return m_scheduler;
	}
}
